package plugin.util;

import java.io.File;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.myframework.util.ExceptionUtil;

public class EclipseUtil {
	private static Log logger ;

//	static{
//		initLog4j();
//
//	}


	private EclipseUtil() {

	}

	public static void setLog(Log log) {
		EclipseUtil.logger = log;
	}

	public static String findEclipseInstall() {
		String eclipsePath = Platform.getInstallLocation().getURL().getPath();
		return eclipsePath;
	}


	/**
	 *  用编辑器打开外部文件
	 * @param page
	 * @param osPath
	 */
	public static void openEditorOnFileStore(IWorkbenchPage page, String osPath) {
		IPath path = Path.fromOSString(osPath);
		IFileStore fileStore = EFS.getLocalFileSystem().getStore(path);
		try {
			IEditorPart part = IDE.openEditorOnFileStore(page, fileStore);
		} catch (PartInitException e1) {
			logger.error(ExceptionUtil.getStackTrace(e1));
		}
	}

	/**
	 * 用编辑器打开外部文件
	 * @param osPath
	 */
	public static void openEditorOnFileStore(String osPath) {
		IWorkbenchPage page = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage();
		IPath path = Path.fromOSString(osPath);
		IFileStore fileStore = EFS.getLocalFileSystem().getStore(path);
		try {
			IEditorPart part = IDE.openEditorOnFileStore(page, fileStore);
			page.activate(part);//page.closeEditor(part, false);
			part.setFocus();
		} catch (PartInitException e1) {
			logger.error(ExceptionUtil.getStackTrace(e1));
		}
	}

	/**
	 * 用文件资源管理器打开目录
	 * @param osPath
	 */
	public static void explore(String osPath) {
		File file = new File(osPath);
		try {
			Runtime.getRuntime().exec("explorer " + file.getAbsolutePath()); //$NON-NLS-1$
			logger.info("explorer " + osPath);
		} catch (IOException e) {
			logger.error(ExceptionUtil.getStackTrace(e));
		}
	}


	public static void main(String[] args){
		File file = new File("/F:/eclipse-jee-luna-R-64//dropins/codegen/templates");
//		log.info(file.getAbsolutePath());
		explore(file.getAbsolutePath());
	}
}
